package com.agenda.daoHibernate;

import java.util.List;

import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.criterion.Example;
import org.hibernate.criterion.MatchMode;
import org.hibernate.criterion.Restrictions;

import util.HibernateUtil;

import com.agenda.dao.MilestoneDao;
import com.agenda.entity.Atividade;
import com.agenda.entity.Milestone;

public class MilestoneDaoHibernate implements MilestoneDao {

	private Session sessao;
	
	@Override
	public String save(Milestone milestone) {
		if((milestone.getIdMilestone() == null) || (milestone.getIdMilestone() == 0)) {
			this.sessao = HibernateUtil.getSession().getCurrentSession();
			this.sessao.save(milestone);		
			return "save";
		} else {
			this.sessao = HibernateUtil.getSession().getCurrentSession();
			this.sessao.update(milestone);
			this.sessao.flush();
			this.sessao.refresh(milestone);
			return "edit";
		}
	}

	public Session getSessao() {
		return sessao;
	}

	public void setSessao(Session sessao) {
		this.sessao = sessao;
	}
	
	@Override
	public List<Milestone> list() {
		try {
			this.sessao = HibernateUtil.getSession().getCurrentSession();
			List<Milestone> lista = (List<Milestone>) this.sessao.createQuery("From Milestone ").list();
			return lista;
		} catch (Exception e) {
			System.out.println("Erro no DaoHibernate: " + e);
		}

		return null;
	}
	
	@Override
	public List<Milestone> find(Milestone milestone) {
		this.sessao =  HibernateUtil.getSession().getCurrentSession();
//		Example example = Example.create(milestone);
//		example.enableLike(MatchMode.START);
//		example.ignoreCase();
//		List listaMilestone = this.sessao.createCriteria(Milestone.class).add(example).list();
		
		if(milestone.getDescricao() == null) {
			try {
				List<Milestone> listaMilestone = this.sessao.createCriteria(Milestone.class).list();
				return listaMilestone;
			} catch (Exception e) {
				return null;
			}
		} else {
		
		try {
			List<Milestone> listaMilestone = this.sessao.createCriteria(Milestone.class)
												.add(Restrictions.like("descricao", milestone.getDescricao(), MatchMode.ANYWHERE).ignoreCase())
												.list();
			return listaMilestone;
		} catch (Exception e) {
			return null;
		}
		}
	}
	
	
	@Override
	public List<Milestone> findByPrimaryKey(Milestone milestone) {
		Integer idMilestone = milestone.getIdMilestone();
		this.sessao = HibernateUtil.getSession().getCurrentSession();
		String hql = "from Milestone a where a.idMilestone = :idMilestone";
		Query select = this.sessao.createQuery(hql);
		select.setInteger("idMilestone", idMilestone);
		List listaMilestone = select.list();
		return listaMilestone;
	}

	@Override
	public void delete(Milestone milestone) {
		this.sessao = HibernateUtil.getSession().getCurrentSession();
		this.sessao.delete(milestone);		
	}

	
}
